package com.adtech.farmProducts.activities.fragment;

import android.Manifest;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Bitmap;
import android.net.Uri;
import android.os.Build;
import android.provider.MediaStore;
import android.support.annotation.NonNull;
import android.support.v4.content.FileProvider;
import android.util.DisplayMetrics;
import android.view.View;
import android.view.WindowManager;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.adtech.common.Common;
import com.adtech.common.http.AsyncHttpPostFormData;
import com.adtech.common.http.AsyncHttpResponse;
import com.adtech.common.http.AsyncOkHttpClient;
import com.adtech.common.http.AsyncResponseHandler;
import com.adtech.common.model.RspModel;
import com.adtech.common.utils.AccountManagers;
import com.adtech.common.utils.FileUtil;
import com.adtech.common.widgets.CircleImageView;
import com.adtech.farmProducts.App;
import com.adtech.farmProducts.R;
import com.adtech.farmProducts.activities.activity.AboutActivity;
import com.adtech.farmProducts.activities.activity.CommodityManagementListActivity;
import com.adtech.farmProducts.activities.activity.CommodityPriceListActivity;
import com.adtech.farmProducts.activities.activity.OperatingDataActivity;
import com.adtech.farmProducts.activities.activity.UpdatePwdActivity;
import com.adtech.farmProducts.activities.activity.UserListActivity;
import com.adtech.farmProducts.base.BaseFragment;
import com.adtech.farmProducts.model.FUserInfo;
import com.adtech.farmProducts.model.VersionUpdate;
import com.adtech.farmProducts.utils.AppUtil;
import com.allenliu.versionchecklib.v2.AllenVersionChecker;
import com.allenliu.versionchecklib.v2.builder.DownloadBuilder;
import com.allenliu.versionchecklib.v2.builder.UIData;
import com.allenliu.versionchecklib.v2.callback.ForceUpdateListener;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import com.gyf.barlibrary.ImmersionBar;

import java.io.File;
import java.io.IOException;
import java.lang.reflect.Type;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.Locale;

import butterknife.BindView;
import butterknife.OnClick;
import pub.devrel.easypermissions.AppSettingsDialog;
import pub.devrel.easypermissions.EasyPermissions;


/**
 * 个人中心
 */
public class MineFragment extends BaseFragment implements
        EasyPermissions.PermissionCallbacks {

    @BindView(R.id.iv_head_portrait)
    CircleImageView ivHeadPotrait;
    @BindView(R.id.tv_name)
    TextView tvName;
    @BindView(R.id.btn_user)
    LinearLayout btn_user;
    @BindView(R.id.tv_version)
    TextView tvVersion;

    @Override
    protected int getLayoutSourceId() {
        return R.layout.fragment_mine;
    }

    @Override
    protected void initImmersionBar() {
        super.initImmersionBar();
        ImmersionBar.with(this)
                .statusBarColor(R.color.trans).init();
    }

    @Override
    protected void initData() {
        super.initData();
        FUserInfo info = new Gson().fromJson(AccountManagers.getAccount(), FUserInfo.class);
        if (info != null) {
            if (info.getUserType() == 1) {
                btn_user.setVisibility(View.VISIBLE);
            } else {
                btn_user.setVisibility(View.GONE);
            }
            tvName.setText(info.getMobile());
        }
        StringBuilder builder = new StringBuilder();
        builder.append("版本更新（当前版本");
        builder.append(getVersionName());
        builder.append(")");
        tvVersion.setText(builder);
    }

    @OnClick({R.id.iv_head_portrait, R.id.tv_name, R.id.btn_user, R.id.btn_insert_list, R.id.btn_commodity_management, R.id.btn_price_management, R.id.btn_update_version, R.id.btn_update_login_pwd, R.id.btn_about, R.id.btn_exit})
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btn_insert_list://录入记录
                OperatingDataActivity.show(mContext);
                break;
            case R.id.btn_user://用户管理
                UserListActivity.show(mContext);
                break;
            case R.id.btn_commodity_management://商品信息管理
                CommodityManagementListActivity.show(mContext, 1);
                break;
            case R.id.btn_price_management://商品价格管理
                CommodityPriceListActivity.show(mContext);
                break;
            case R.id.iv_head_portrait://拍照
                //checkAndRequestPermission(); // 检查并申请权限
                break;
            case R.id.tv_name:
                break;
            case R.id.btn_update_version://版本更新
                getUpdateVersion();
                break;
            case R.id.btn_update_login_pwd://修改登录密码
                UpdatePwdActivity.show(mContext);
                break;
            case R.id.btn_about://关于
                AboutActivity.show(mContext);
                break;
            case R.id.btn_exit://退出
                showNormalDialog();
                break;
        }
    }

    private void showNormalDialog() {
        AlertDialog.Builder normalDialog =
                new AlertDialog.Builder(mContext);
        normalDialog.setTitle("提示");
        normalDialog.setMessage("您确定要退出软件?");
        normalDialog.setPositiveButton("确定",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        AccountManagers.logOut();
                        AppUtil.finishAll();
                    }
                });
        normalDialog.setNegativeButton("取消",
                new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                    }
                });
        normalDialog.show();
    }


    /**
     * 版本更新
     */
    public void getUpdateVersion() {
        loadingDialogShow(true);
        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
        AsyncHttpPostFormData asyncHttpPostFormData = new AsyncHttpPostFormData();
        okHttpClient.posts(Common.Constant.API_IP + "appVersion/lastVersion", asyncHttpPostFormData, new AsyncResponseHandler() {
            @Override
            public void onFailure(IOException e) {
                App.getInstance().showMessage(getResources().getString(R.string.network_timeout));
                onDismiss();
                e.printStackTrace();
            }

            @Override
            public void onSuccess(AsyncHttpResponse response) {
                onDismiss();
                Type type = new TypeToken<RspModel<VersionUpdate>>() {
                }.getType();
                RspModel<VersionUpdate> rspModel = getAnalysis(response, type, "版本更新");
                if (rspModel == null) {
                    return;
                }
                if (rspModel.getCode() == 1) {
                    try {
                        int versionCode = getVersionCode();
                        if (rspModel.getData().getVersion() > versionCode) {
                            updateVersion(rspModel.getData().getIs_forced(), rspModel.getData().getDescription(), rspModel.getData().getApk_url());
                        } else {
                            App.getInstance().showMessage("当前已是最新版本！");
                        }
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            }
        });
    }

    private void dialogWidth(Dialog baseDialog) {
        WindowManager.LayoutParams lp = baseDialog.getWindow().getAttributes();
        DisplayMetrics dm = new DisplayMetrics();
        getActivity().getWindowManager().getDefaultDisplay().getMetrics(dm);
        lp.width = (int) (dm.widthPixels * 0.92); //设置宽度
        baseDialog.getWindow().setAttributes(lp);
    }

    private void updateVersion(final int force, String content, String url) {
        DownloadBuilder downloadBuilder = AllenVersionChecker.getInstance().downloadOnly(
                UIData.create().setTitle("是否更新?").setContent(content).setDownloadUrl(url)
        );
        downloadBuilder.setSilentDownload(false); //默认false
        downloadBuilder.setForceRedownload(true); //默认false 本地有安装包缓存也会重新下载apk
        downloadBuilder.executeMission(mContext);
        if (force == 1) {//强制更新
            //是否显示下载对话框
            downloadBuilder.setShowDownloadingDialog(true);// 默认true
            downloadBuilder.setForceUpdateListener(new ForceUpdateListener() {
                @Override
                public void onShouldForceUpdate() {
                }
            });
        } else {
            downloadBuilder.setShowDownloadingDialog(false);
        }
    }

    /**
     * 显示我的碎片
     *
     * @return MineFragment
     */
    public static MineFragment newInstance() {
        return new MineFragment();
    }


    public static final int PERMISSION_REQUEST_CODE = 1;
    // 定义相关权限
    private String[] mCameraPerms = new String[]{
            Manifest.permission.CAMERA//, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.READ_EXTERNAL_STORAGE
    };


    // 定义拍照和相册裁剪操作的请求码
    private static final int CAMERA_REQUEST_CODE = 5000;
    private static final int GALLERY_REQUEST_CODE = 5001;
    private static final int CROP_REQUEST_CODE = 5002;

    // Android7.0 以上系统图片的Uri地址
    private Uri mProviderUri;

    // Android7.0 以下系统图片的Uri地址
    private Uri mUri;

    /**
     * 更新头像
     */
//    private void showUpdateDialogFragment() {
//        // 显示一个提示的dialog
//        UpdatePortraitDialogFragment updatePortraitDialogFragment
//                = UpdatePortraitDialogFragment.newInstance(this);
//        if (!updatePortraitDialogFragment.isAdded()) {
//            updatePortraitDialogFragment.show(getChildFragmentManager(),
//                    updatePortraitDialogFragment.getClass().getName());
//        }
//    }

    /**
     * 拍照片
     */
    private void camera() {
        //使用当前系统的日期加以调整作为照片的名称
        Date date = new Date(System.currentTimeMillis());
        //创建日期格式转换对象
        SimpleDateFormat dataFormat = new SimpleDateFormat("'IMG'_yyyyMMdd_HHmmss", Locale.getDefault());
        SimpleDateFormat.getDateInstance();
        // 定义Image图片的文件名
        String imageFileName = dataFormat.format(date) + ".jpg";
        // 获取储存头像图片文件夹的路径
        String portraitDirName = FileUtil.createAppFoldersRootPath() + File.separator + "Pictures";

        File imageFile = new File(portraitDirName, imageFileName);
        // 如果储存图片文件的目录没有创建则进行创建的操作
        if (!imageFile.getParentFile().exists()) {
            if (!imageFile.getParentFile().mkdirs()) {
                App.getInstance().showMessage(getResources().getString(R.string.toast_none));
            }
        }
        // 创建一个打开相机的意图
        Intent intent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
        // Android7.0 以上
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            //通过FileProvider创建一个content类型的Uri
            mProviderUri = FileProvider.getUriForFile(mContext, "com.adtech.medicinemanagement.fileprovider", imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mProviderUri);
            // 添加这一句表示对目标应用临时授权该Uri所代表的文件
            intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
        } else {
            mUri = Uri.fromFile(imageFile);
            intent.putExtra(MediaStore.EXTRA_OUTPUT, mUri);
        }
        // 启动相机
        startActivityForResult(intent, CAMERA_REQUEST_CODE);
    }


    /**
     * 跳转到相册
     */
    private void gallery() {
        // 创建意图对象
        Intent intent = new Intent(Intent.ACTION_PICK,
                MediaStore.Images.Media.EXTERNAL_CONTENT_URI);

        intent.setDataAndType(MediaStore.Images.Media.EXTERNAL_CONTENT_URI, "image/*");

        startActivityForResult(intent, GALLERY_REQUEST_CODE);
    }


    /**
     * 头像上传
     *
     * @param bitmap Bitmap
     */
    private void upHeardImage(Bitmap bitmap) {
        ivHeadPotrait.setImageBitmap(bitmap);
//        loadingDialogShow(false);
//        ByteArrayOutputStream stream = new ByteArrayOutputStream();
//        bitmap.compress(Bitmap.CompressFormat.PNG, 60, stream);
//        byte[] bytes = stream.toByteArray();
//        //base64 encode
//        String encodeString = Base64.encodeToString(bytes, Base64.DEFAULT);
//        AsyncOkHttpClient okHttpClient = new AsyncOkHttpClient();
//        AsyncHttpPostFormData AsyncHttpPostFormData = new AsyncHttpPostFormData();
//        AsyncHttpPostFormData.addFormData("image_path", "data:image/png;base64," + encodeString);
//        okHttpClient.post("/v1/user/save-heard-img", AsyncHttpPostFormData, new AsyncResponseHandler() {
//            @Override
//            public void onFailure(IOException e) {
//                onDismiss();
//                e.printStackTrace();
//            }
//
//            @Override
//            public void onSuccess(AsyncHttpResponse response) {
//                onDismiss();
//            }
//        });
    }


    /**
     * 重写权限请求的方法
     */
    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
        // 把权限申请的执行结果的操作给EasyPermissions
        EasyPermissions.onRequestPermissionsResult(requestCode, permissions, grantResults, this);
    }


    /**
     * 申请权限成功
     */
    @Override
    public void onPermissionsGranted(int requestCode, @NonNull List<String> perms) {
        // 如果权限申请成功
        if (EasyPermissions.hasPermissions(mContext, mCameraPerms)) {
        }
    }

    /**
     * 申请权限失败
     */
    @Override
    public void onPermissionsDenied(int requestCode, @NonNull List<String> perms) {
        //处理权限名字字符串
        StringBuilder sb = new StringBuilder();
        for (String str : perms) {
            sb.append("(");
            sb.append(str);
            sb.append(")");
            sb.append("\n");
        }
        String message = sb.append("\n").toString();

        if (EasyPermissions.somePermissionPermanentlyDenied(this, perms)) {
            new AppSettingsDialog.Builder(this)
                    .setTitle("提示")
                    .setRationale("更新头像需要以下权限：" + message + "是否打开设置界面进行授权？")
                    .setPositiveButton("是")
                    .setNegativeButton("否")
                    .build()
                    .show();
        }
    }
}
